import { reactive } from "vue";
import { Local } from "../utils/storage";

interface RestaurantItem {
    value: string
    link: string
    data: any
}
export class InputStore {
    restaurants = reactive<RestaurantItem[]>([]);
    oldInps: any[] = []
    localName = ''
    callGetInp?: (val: any) => void
    constructor(localName: string, callGetInp?: (val: any) => void) {
        this.localName = localName
        this.callGetInp = callGetInp
    }

    loadOldInp() {
        this.restaurants.length = 0
        this.oldInps = Local.get(this.localName) || []
        for (const oldInp of this.oldInps) {
            this.restaurants.push({
                value: this.callGetInp?.(oldInp) || (oldInp + ''), link: '', data: oldInp
            })
        }
    }

    addOldInp(inp: any) {
        if (!inp) return
        const cgi = this.callGetInp, oldInps = this.oldInps

        for (let i = oldInps.length - 1; i > -1; i--) {
            const oldInp = oldInps[i]
            if (cgi) {
                if (cgi(oldInp) === cgi(inp)) {
                    oldInps.splice(i, 1)
                    break
                }
            } else if (oldInp === inp) {
                oldInps.splice(i, 1)
                break
            }
        }
        oldInps.splice(0, 0, inp)
        Local.set(this.localName, oldInps)
    }

    queryOldInps(queryString: string, cb: any) {
        const results = queryString
            ? this.restaurants.filter(this.createFilter(queryString))
            : this.restaurants
        cb(results)
        return results
    }

    createFilter(queryString: string) {
        return (restaurant: RestaurantItem) => {
            return (
                restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
            )
        }
    }
}